# -*- coding: utf-8 -*-
'''
@Time    : 2021/3/16 20:18
@Author  : wenhaha
@File    : MyForms.py
'''

from django import forms
from django.core.exceptions import ValidationError
from django.forms import widgets

from blogSystem1.models import UserInfo


class UserForm(forms.Form):
    user = forms.CharField(max_length=32,
                           error_messages={
                               'required': '请输入用户名！',
                           },
                           label='用户名',
                           widget=widgets.TextInput(
                               attrs={
                                   'class': 'form-control',
                                   'id': 'user',
                               }))
    password = forms.CharField(max_length=32,
                               error_messages={
                                   'required': '请输入密码！',
                               },
                               required='请输入',
                               label='密码',
                               widget=widgets.PasswordInput(
                                   attrs={
                                       'class': 'form-control',
                                       'id': 'password',
                                   }))
    re_password = forms.CharField(max_length=32,
                                  error_messages={
                                      'required': '请输入密码！',
                                  },
                                  label='确认密码',
                                  widget=widgets.PasswordInput(
                                      attrs={
                                          'class': 'form-control',
                                          'id': 're_password',
                                      }))
    email = forms.EmailField(max_length=32,
                             error_messages={
                                 'required': '请输入邮箱！',
                             },
                             label='邮箱',
                             widget=widgets.EmailInput(
                                 attrs={
                                     'class': 'form-control',
                                     'id': 'email',
                                 }))

    # 局部钩子处理用户名重复
    def clean_username(self):
        username = self.cleaned_data.get("user")
        user = UserInfo.objects.filter(username=username).first()
        if not user:
            return username
        else:
            raise ValidationError("该用户已注册！")

    # 全局钩子处理密码不一致
    def clean(self):
        pwd = self.cleaned_data.get('password')
        re_pwd = self.cleaned_data.get('re_password')

        if pwd and re_pwd:
            if pwd == re_pwd:
                return self.cleaned_data
            else:
                raise ValidationError('两次密码不一致！')
        else:
            return self.cleaned_data
